﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GSLMS.Core;
using GSLMS.Entity;
using GSLMS.Services.Interface;
using System.Threading;
using GSLMS.Entity.DTO;
using GSLMS.Entity.Enum;

namespace GSLMS.WebAPP
{
    public class AdminBaseController : Controller
    {
        #region Init Config Interface
        protected static readonly IFileManage serviceFileManage = ServiceFactory.LazyT<IFileManage>();
        protected static readonly IModule serviceModule = ServiceFactory.LazyT<IModule>();
        protected static readonly IRoles serviceRoles = ServiceFactory.LazyT<IRoles>();
        protected static readonly IDictionary serviceDictionary = ServiceFactory.LazyT<IDictionary>();
        protected static readonly ISystemConfig serviceSystemConfig = ServiceFactory.LazyT<ISystemConfig>();
        //protected static readonly IManager servicesManager = ServiceFactory.LazyT<IManager>();
        protected static readonly IDictionary serviceDict = ServiceFactory.LazyT<IDictionary>();
        protected static readonly IArea serviceArea = ServiceFactory.LazyT<IArea>();

        #endregion
        #region Init logic Interface
        protected static readonly IAPP_REGINFO serviceRegInfo = ServiceFactory.LazyT<IAPP_REGINFO>("IAPP_REGINFO");
        protected static readonly IAPP_SPECIALINFO serviceSpecailInfo = ServiceFactory.LazyT<IAPP_SPECIALINFO>("IAPP_SPECIALINFO");
        protected static readonly IAPP_REFREGINFO serviceRefRegInfo = ServiceFactory.LazyT<IAPP_REFREGINFO>("IAPP_REFREGINFO");
        protected static readonly IAPP_PROINFO serviceProInfo = ServiceFactory.LazyT<IAPP_PROINFO>("IAPP_PROINFO");
        protected static readonly IAPP_LOGINFO serviceLogInfo = ServiceFactory.LazyT<IAPP_LOGINFO>("IAPP_LOGINFO");
        protected static readonly IAPP_PROTARINFO serviceProTarInfo = ServiceFactory.LazyT<IAPP_PROTARINFO>("IAPP_PROTARINFO");
        protected static readonly IAPP_PROMETINFO serviceProMetInfo = ServiceFactory.LazyT<IAPP_PROMETINFO>("IAPP_PROMETINFO");
        protected static readonly IAPP_PROCONINFO serviceProConInfo = ServiceFactory.LazyT<IAPP_PROCONINFO>("IAPP_PROCONINFO");
        protected static readonly IAPP_PROCOMINFO serviceProComInfo = ServiceFactory.LazyT<IAPP_PROCOMINFO>("IAPP_PROCOMINFO");
        protected static readonly IAPP_PROFILESINFO serviceProFilesInfo = ServiceFactory.LazyT<IAPP_PROFILESINFO>("IAPP_PROFILESINFO");
        protected static readonly ILOAN_RETURN serviceLoanReturn = ServiceFactory.LazyT<ILOAN_RETURN>("ILOAN_RETURN");
        protected static readonly ISYS_EMP serviceEmp = ServiceFactory.LazyT<ISYS_EMP>("ISYS_EMP");
        protected static readonly ILOAN_MAIN serviceLoanMain = ServiceFactory.LazyT<ILOAN_MAIN>("ILOAN_MAIN");
        protected static readonly IADU_ASSIGN serviceAduAssign = ServiceFactory.LazyT<IADU_ASSIGN>("IADU_ASSIGN");
        protected static readonly ILOAN_CONTRACT serviceLoanContract = ServiceFactory.LazyT<ILOAN_CONTRACT>("ILOAN_CONTRACT");
        protected static readonly IREST_CHANNEL serviceRestChannel = ServiceFactory.LazyT<IREST_CHANNEL>("IREST_CHANNEL");
        protected static readonly ISYS_PRODUCT serviceSysProduct = ServiceFactory.LazyT<ISYS_PRODUCT>("ISYS_PRODUCT");
        protected static readonly ISYS_ORG serviceSysOrg = ServiceFactory.LazyT<ISYS_ORG>("ISYS_ORG");
        protected static readonly ISYS_LOG serviceSysLog = ServiceFactory.LazyT<ISYS_LOG>("ISYS_LOG");
        protected static readonly ISYS_PARM serviceSysParm = ServiceFactory.LazyT<ISYS_PARM>("ISYS_PARM");
        protected static readonly ISYS_AUDITSET serviceSysAuditSet = ServiceFactory.LazyT<ISYS_AUDITSET>("ISYS_AUDITSET");
        protected static readonly ISYS_METINFOSETMAIN serviceSysMetinfoSet = ServiceFactory.LazyT<ISYS_METINFOSETMAIN>("ISYS_METINFOSETMAIN");
        protected static readonly ISYS_SURVEYTMPSET serviceSysSurveyTmpSet = ServiceFactory.LazyT<ISYS_SURVEYTMPSET>("ISYS_SURVEYTMPSET");
        protected static readonly ISYS_USERPRIV serviceSysUserPriv = ServiceFactory.LazyT<ISYS_USERPRIV>("ISYS_USERPRIV");
        protected static readonly IAPP_AUDIT serviceAppAudit = ServiceFactory.LazyT<IAPP_AUDIT>("IAPP_AUDIT");
        protected static readonly IADU_SPECAIL serviceSpecail = ServiceFactory.LazyT<IADU_SPECAIL>("IADU_SPECAIL");
        protected static readonly ICOL_LOANEXT serviceLoanExt = ServiceFactory.LazyT<ICOL_LOANEXT>("ICOL_LOANEXT");
        protected static readonly ICOL_FEESFREE serviceFeesFree = ServiceFactory.LazyT<ICOL_FEESFREE>("ICOL_FEESFREE");
        protected static readonly IADU_REFREGASS serviceRefRegAss = ServiceFactory.LazyT<IADU_REFREGASS>("IADU_REFREGASS");
        protected static readonly IADU_CONARR serviceAduConArr = ServiceFactory.LazyT<IADU_CONARR>("IADU_CONARR");
        protected static readonly IADU_CONADU serviceAduConAdu = ServiceFactory.LazyT<IADU_CONADU>("IADU_CONADU");
        protected static readonly IADU_CONSUM serviceAduConSum = ServiceFactory.LazyT<IADU_CONSUM>("IADU_CONSUM");

        protected static readonly ILOAN_CONTRACTTMP serviceContractTmp = ServiceFactory.LazyT<ILOAN_CONTRACTTMP>("ILOAN_CONTRACTTMP");
        protected static readonly ILOAN_CONTRACT serviceContract = ServiceFactory.LazyT<ILOAN_CONTRACT>("ILOAN_CONTRACT");

        #endregion

        protected static readonly int pageSize = Helper.PageSize;
        protected string sort = "";
        protected string order = "";
        protected int pageNumber = 1;

        /// <summary>
        /// 列表视图
        /// </summary>
        protected string viewList = string.Empty;
        /// <summary>
        /// 创建或修改视图
        /// </summary>
        protected string viewCreate = string.Empty;

        protected string ajaxStr = HelperCommon.AJAXFORMAT;
        private UniversallySearchParam _SearchParma = new UniversallySearchParam() { Pagination = new PaginationDTO() { CurrentIndex = 1, PageSize = pageSize } };
        protected UniversallySearchParam UniversallySearchParma
        {
            get { return _SearchParma; }
            set { _SearchParma = value; }
        }

        /// <summary>
        /// navTab ID
        /// </summary>
        protected virtual string navTabId { get; set; }

        private CurrentUserDTO _CurentUser = new CurrentUserDTO() { UserName = "admin" };
        public CurrentUserDTO CurentUser
        {
            get
            {
                return _CurentUser;
            }
            set { _CurentUser = value; }
        }

        public string OperateID
        {
            get { return Session["OperateID"] as string; }
            set { Session["OperateID"] = ViewData["OperateID"] = value; }
        }

        public object AreaName { get; set; }
        public object ControllerName { get; set; }
        public object ActionName { get; set; }
        public string DIVGUID { get; set; }
        protected string AjaxResultSucess
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
            }
        }



        protected string AjaxResultFail
        {
            get
            {
                return string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
        }

        protected string AjaxDeleteSucess
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 200, ResourceManager.DeleteSuccess, navTabId, "", "forward");
            }
        }

        protected string AjaxDeleteFail
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }
        }

        protected string AjaxActionSucess(string showTips)
        {
            return string.Format(HelperCommon.AJAXFORMAT, 200, showTips, navTabId, "", "forward");
        }

        protected string AjaxActionFail(string showTips)
        {
            return string.Format(HelperCommon.AJAXFORMAT, 300, showTips, navTabId, "", "");
        }



        [ValidateInput(false)]
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //SetUser();//测试用
            if (Session["CurentUser"] != null)
            {
                CurentUser = Session["CurentUser"] as CurrentUserDTO;
            }
            else
            {
                new AdminAttribute().OnActionExecuting(filterContext);
            }

            AreaName = filterContext.RouteData.DataTokens["area"];
            ControllerName = filterContext.RouteData.Values["controller"];
            ActionName = filterContext.RouteData.Values["action"];

            #region 设置当前页面
            int currentIndex = 1;
            if (Request["pageNum"] != null)
            {
                int.TryParse(Request["pageNum"], out currentIndex);
            }
            UniversallySearchParma.Pagination.CurrentIndex = currentIndex;
            #endregion

            #region 设置共用搜索参数
            InitSearchParmater();

            #endregion

            #region 设置是否需要重新计算总记录
            if (Request["RowCount"] != null)
            {
                int rowCount = 0;
                int.TryParse(Request["RowCount"], out rowCount);
                UniversallySearchParma.Pagination.RowCount = rowCount;
            }
            #endregion
            navTabId = string.Format("{0}{1}", AreaName, ControllerName).ToLower();
            ViewData["CurrentController"] = navTabId;


            //#region 设置当前用户是否只能看下属
            //if (CurentUser.Roles.Where(c => c.ID == "Users_6").FirstOrDefault() != null)
            //{
            //    SearchParma.OnlySon = CurentUser.CurrentUserInfo.ID;
            //}
            //#endregion

            //string LangType = Request["LangType"];
            //var reSearchDiv = string.Format("div{0}{1}", ViewData["CurrentController"], LangType);
            //ViewData["LangType"] = LangType ?? "0";
            //ViewData["reSearchDiv"] = reSearchDiv;

            ViewData["GUID"] = Guid.NewGuid();
            DIVGUID = string.Format("{0},{1}", Request["DIVGUID"], Request["LangType"]);

            string opID = Request["OpID"];
            //opID = opID ?? OperateID;
            OperateID = opID;
        }

        private void InitSearchParmater()
        {
            //if (CurentUser.SubEmp != null && !Helper.SuperUsers.Contains(CurentUser.CurrentUserInfo.USERNAME))
            //{
            //    UniversallySearchParma.SubAssignedIn = CurentUser.SubEmp.Select(c => c.ID).ToList<int>();
            //    UniversallySearchParma.SubAssignedIn = UniversallySearchParma.SubAssignedIn ?? new List<int>();
            //    UniversallySearchParma.SubAssignedIn.Add(CurentUser.CurrentUserInfo.ID);
            //}

            //if (CurentUser.SubManager != null && !Helper.SuperUsers.Contains(CurentUser.CurrentUserInfo.USERNAME))
            //{
            //    UniversallySearchParma.SubAssignedIn = CurentUser.SubManager.Select(c => c.ID).ToList<int>();
            //    UniversallySearchParma.SubAssignedIn = UniversallySearchParma.SubAssignedIn ?? new List<int>();
            //    UniversallySearchParma.SubAssignedIn.Add(CurentUser.CurrentUserInfo.ID);
            //}

            UniversallySearchParma.Ttile = Request["Title"];
            DateTime startime = DateTime.MinValue;
            DateTime endtime = DateTime.MinValue;
            if (Request["StarTime"] != null)
            {
                if (DateTime.TryParse(Request["StarTime"], out startime))
                {
                    { UniversallySearchParma.StarDateTime = startime; }
                }
            }
            if (Request["EndTime"] != null)
            {
                if (DateTime.TryParse(Request["EndTime"], out endtime))
                { UniversallySearchParma.EndDateTime = endtime; }
            }

            UniversallySearchParma.Creator = Request["Creator"];
            UniversallySearchParma.Updater = Request["Updater"];
            int IntObj1 = 0;
            if (!String.IsNullOrEmpty(Request["IntObj1"]))
            {
                int.TryParse(Request["IntObj1"], out IntObj1);
                UniversallySearchParma.IntObj1 = IntObj1;
            }
            if (!String.IsNullOrEmpty(Request["IntObj2"]))
            {
                int.TryParse(Request["IntObj2"], out IntObj1);
                UniversallySearchParma.IntObj2 = IntObj1;
            }

        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            ViewData["CurrentPageButtons"] = new List<VRolePurview>();
            if (CurentUser != null && CurentUser.Roles != null)
            {
                string currentUrl = Request.FilePath;
                //var currentModule = CurentUser.Roles.Where(c => !string.IsNullOrEmpty(c.Url)
                //                                            && c.Url.IndexOf(ActionName as string) >= 0
                //                                            && c.Url.IndexOf(ControllerName as string) >= 0
                //                                            && c.Types == (int)CommEnum.ModuleTypes.模块)
                //                                            .FirstOrDefault();
                var currentModule = CurentUser.Roles.Where(c => c.ID == OperateID).FirstOrDefault();
                var currentButtons = new List<VRolePurview>();
                var currentFuncs = new List<VRolePurview>();
                if (currentModule != null)
                {
                    currentButtons = CurentUser.Roles.Where(c => c.Parent == currentModule.ID && c.Types == (int)CommEnum.ModuleTypes.按钮).OrderBy(c => c.Order).ToList();
                    currentFuncs = CurentUser.Roles.Where(c => c.Parent == currentModule.ID && c.Types == (int)CommEnum.ModuleTypes.功能点).OrderBy(c => c.Order).ToList();
                }
                ViewData["CurrentPageButtons"] = currentButtons;
                ViewData["CurrentPageFuncs"] = currentFuncs;
            }

            int nPageSize = pageSize;
            if (UniversallySearchParma != null && UniversallySearchParma.Pagination != null)
            {
                if (UniversallySearchParma.Pagination.PageSize == Int32.MaxValue)
                    nPageSize = 0;
                if (UniversallySearchParma.Pagination.PageSize != 0)
                    nPageSize = UniversallySearchParma.Pagination.PageSize;
            }
            ViewData["pageSize"] = nPageSize;
            ViewData["PhotoWidth"] = Helper.PhotoWidth;
            ViewData["PhotoHeight"] = Helper.PhotoHeight;
            ViewData["UniversallySearchParma"] = UniversallySearchParma;
            LogOperation(filterContext);

        }
        protected void ExceptionHand(Exception e)
        {
            new Loger().ExceptionHand(e);
        }

        protected override void OnException(ExceptionContext errorContext)
        {
            errorContext.Result = new RedirectResult(Url.Action("Error", "Shared"));
        }

        protected virtual bool MoveToFile(string guid, string newFile, out string newpath)
        {
            bool tag = false;
            newpath = string.Empty;
            try
            {
                var fileManage = serviceFileManage.GetByGuid(guid);
                //string newFile = "Email";
                foreach (var item in fileManage)
                {
                    if (item.FilePath.IndexOf("Temp") > 0)
                    {
                        FileManagement.MoveToFile(item.FilePath, item.FilePath.Replace("Temp", newFile));
                        item.FilePath = item.FilePath.Replace("Temp", newFile);
                        newpath = item.FilePath;
                        serviceFileManage.Update(item);
                    }
                }
                tag = true;
            }
            catch
            { }
            return tag;

        }

        protected List<TB_SYS_EMP> GetManagersByLevel(bool isLevel = true)
        {
            long parentID = 0;
            //if (CurentUser.Roles.Where(c => c.ID == "Users_6").FirstOrDefault() != null)
            //{
            //    parentID = CurentUser.CurrentUserInfo.ID;

            //}
            if (CurentUser.CurrentUserInfo.USERTYPE != 1)
            { parentID = CurentUser.CurrentUserInfo.ID; }

            //获取所有层信息
            //return servicesManager.GetAllByLevel(parentID, isLevel);
            var list = new List<TB_SYS_EMP>();
            return list;
        }

        protected SelectList GetListFromDict(string groupName, bool IsSelectLabel = false, object selected = null)
        {
            var lst = serviceDict.GetByGroupName(groupName, 1) ?? new List<Dictionary>();
            if (IsSelectLabel)
            {
                lst.Insert(0, new GSLMS.Entity.Dictionary() { key = "-100", Value = HelperCommon.SelectDefaultValue });
            }
            SelectList sList = new SelectList(lst, "Value", "Value", selected);
            return sList;
        }

        protected TModel SearchPara<TModel>(FormCollection form, TModel t) where TModel : class,new()
        {
            if (form != null && form.Count > 0)
            {
                TryUpdateModel(t, form);
            }
            if (t == null)
            {
                t = new TModel();
            }
            else
            {
                var objType = t.GetType();
                if (UniversallySearchParma.SubAssignedIn != null && UniversallySearchParma.SubAssignedIn.Count > 0)
                {
                    objType.GetProperty("SubAssignedIn").SetValue(t, UniversallySearchParma.SubAssignedIn, null);
                }
                if (UniversallySearchParma.Pagination != null)
                {
                    objType.GetProperty("Pagination").SetValue(t, UniversallySearchParma.Pagination ?? new PaginationDTO(), null);
                }
            }
            ViewData["SearchParma"] = t;
            return t;
        }



        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="filterContext"></param>
        private void LogOperation(ActionExecutedContext filterContext)
        {

            if (!string.IsNullOrEmpty(OperateID))
            {
                var role = CurentUser.Roles.SingleOrDefault(c => c.ID == OperateID);
                if (role != null)
                {
                    var logOp = new OperationLogDTO();
                    logOp.ID = OperateID;
                    logOp.ModuleName = role.ModuleName;
                    logOp.URL = role.Url;
                    logOp.Detail = role.Title;
                    logOp.Operater = CurentUser.UserName;
                    logOp.OpTime = DateTime.Now;

                    string parameters = string.Empty;
                    foreach (var item in filterContext.RouteData.Values)
                    {
                        parameters += string.Format("{0}={1};", item.Key, item.Value);
                    }
                    logOp.Parameters = parameters;
                    logOp.OperateAction = filterContext.RequestContext.HttpContext.Request.HttpMethod;
                    //Thread thred = new Thread(new ParameterizedThreadStart(WriteOpLog));
                    //thred.Start(logOp);
                    string xml = XmlUtil.Serializer<OperationLogDTO>(logOp);
                    WriteFile wFile = new WriteFile("/OpLog/", LogType.Daily);
                    wFile.Write(new Msg() { Text = xml });
                }
            }
        }

        public void WriteOpLog(object logOp)
        {
            string OplogxmlfilePath = string.Format("{0}/{1}.xml", AppDomain.CurrentDomain.BaseDirectory + "/OpLog", DateTime.Now.ToString("yyyyMMdd"));
            XmlUtil.SerializerToFile<OperationLogDTO>(logOp as OperationLogDTO, OplogxmlfilePath);
        }
        private void SetUser()
        {
            if (Session["CurentUser"] == null)
            {
                string userName = "luochengbang";
                if (Request.Cookies["user"] != null)
                {
                    userName = Request.Cookies["user"].Value;
                }
                TB_SYS_EMP model = new TB_SYS_EMP();
                model = serviceEmp.GetByUserName(userName);
                #region 测试代码

                if (model == null)
                {
                    model = new TB_SYS_EMP();
                }

                model.USERNAME = userName == "" ? "admin" : userName;
                model.USERSTATUS = 1;
                model.IsLogin = true;
                model.USERTYPE = 1;

                #endregion
                CurrentUserDTO curentUser = new CurrentUserDTO();
                if (model.USERTYPE == 1)
                {

                    curentUser.CurrentUserInfo = model;
                    List<VRolePurview> roles = GetRolesFromXML();
                    curentUser.Roles = roles;
                }
                else
                {
                    //获取菜单XML信息
                    // curentUser = servicesManager.GetByUserAndRoles(model.User);
                }
                Session["CurentUser"] = curentUser;
                Response.Cookies["user"].Value = curentUser.CurrentUserInfo.USERNAME;
            }
        }
        private static List<VRolePurview> GetRolesFromXML()
        {
            List<VRolePurview> roles = new List<VRolePurview>();
            var allRoles = HelperCommon.GetModulesFromXML().Where(c => c.Reverse == false || !c.Reverse.HasValue);
            foreach (var c in allRoles)
            {
                roles.Add(
                    new VRolePurview()
                    {
                        Name = "超级管理员",
                        ModulelID = c.ID,
                        ID = c.ID,
                        Title = c.Title,
                        Url = c.Url,
                        Order = c.Order,
                        Remark = c.Remark,
                        GUID = c.GUID,
                        Types = c.Types,
                        ParmFormat = c.ParmFormat,
                        OnCilck = c.OnCilck,
                        Parent = c.Parent,
                        RoleID = -1,
                        CssClass = c.CssClass,
                        Target = c.Target,
                        Fresh = c.Fresh,
                        External = c.External,
                        ModuleName = c.ModuleName,
                        Warn = c.Warn,
                        CallBack = c.CallBack

                    }
                    );
            }
            return roles;
        }


    }
}
